#include "logic.h"
#include "../../log.h"

#include <mutex>
#include <queue>

Logic::Logic() : m_is_stop(false)
{
    _RegisterCallBacks();

    m_work_thread = std::thread([this](){
        while(true)
        {
            std::unique_lock<std::mutex> lock(m_mutex);
            m_cond.wait(lock, [this](){ return m_is_stop || !m_logicNodes.empty(); });
            std::queue<std::shared_ptr<LogicNode>> nodes;
            nodes.swap(m_logicNodes);
            lock.unlock();
            while(!nodes.empty())
            {
                auto node = nodes.front();
                std::shared_ptr<Session> session = node->GetSession();
                auto find = m_call_backs.find(session->GetRecvNode()->m_head->GetMsgId());
                if(find != m_call_backs.end())
                {
                    find->second(session);
                }
                nodes.pop();
            }

            if(m_is_stop)
            {
                break;
            }
        }
    });
}

Logic::~Logic()
{
    m_is_stop = true;
    m_cond.notify_one();
    if(m_work_thread.joinable())
    {
        m_work_thread.join();
    }
}

void Logic::AddLogicNode(const std::shared_ptr<LogicNode>& node)
{
    std::unique_lock<std::mutex> lock(m_mutex);
    m_logicNodes.push(node);
    m_cond.notify_one();
}

Logic& Logic::GetInstance()
{
    static Logic instance;
    return instance;
}


//注册回调函数
void Logic::_RegisterCallBacks()
{
    m_call_backs.insert(std::make_pair(MSG_HELLO_WORLD, [this](const std::shared_ptr<Session>& s){
        HelloWorldCallBack(s);
    }));
}

//MSG_HELLO_WORLD  1001  的回调函数
void Logic::HelloWorldCallBack(const std::shared_ptr<Session>& session)
{
    std::string msg(session->GetRecvNode()->m_data.get(), session->GetRecvNode()->m_head->GetMsgLen());
    log_debug("receive msg:{}", session->GetRecvNode()->m_data.get());

    session->Send(msg.c_str(), msg.length(), session->GetRecvNode()->m_head->GetMsgId());
}